import { ITodoData } from "./typings";
import TodoTemplate from "./TodoTemplate";
import { findParentNode, createItem } from "./utils";

class TodoDom extends TodoTemplate {
  // 需要一个容器 外界传进来的
  private todoWrapper: HTMLElement;

  constructor(todoWrapper: HTMLElement) {
    super()
    this.todoWrapper = todoWrapper
  }
  // protected 只有基类和子类能访问 防止外界访问

  protected initList (todoData: ITodoData[]) { // 初始化视图
    if (todoData.length) {
      // 创建文档碎片, 直接用 todoWrapper.appendChild 会造成性能消耗较大
      const oFrag: DocumentFragment = document.createDocumentFragment();
      todoData.map((item:ITodoData) => {
        const oItem: HTMLElement = createItem('div', 'todo-item', this.todoView(item));
        oFrag.appendChild(oItem);
      });
      this.todoWrapper.appendChild(oFrag);
    }
  }

  protected addItem (todo: ITodoData) {
    // const oItem: HTMLElement = document.createElement("div");
    // oItem.className = 'todo-item';
    // 调用继承来的模板 todoView 渲染视图
    // oItem.innerHTML = this.todoView(todo);
    const oItem: HTMLElement = createItem('div', 'todo-item', this.todoView(todo));
    this.todoWrapper.appendChild(oItem);
  }

  protected removeItem (target: HTMLElement) {
    // 点击哪条数据就删除
    const oParentNode: HTMLElement = findParentNode(target, 'todo-item');
    oParentNode.remove()
  }

  protected changeCompleted (target: HTMLElement, completed: boolean) {
    const oParentNode: HTMLElement = findParentNode(target, 'todo-item');
    const oContent: HTMLElement = oParentNode.getElementsByTagName('span')[0];
    console.log(oContent)

    oContent.style.textDecoration = completed ? 'line-through': 'none';
  }

}

export default TodoDom;